import 'package:flutter/material.dart';

class RefreshLoadState<T extends StatefulWidget, V> extends State {
  ScrollController _scrollController = ScrollController(); //listview的控制器
  int _page = 1;
  bool _hasNext = true;
  int _pageSize = 20;
  List<Widget> _children = [];

  List<V> initData = [];
  Future<List<V>> Function(int page, int pageSize) getPage;
  Widget Function(V v) itemBuilder;
  Widget Function(RefreshIndicator w)? wrapper;
  Widget Function()? noMore;
  List<Widget> Function(List<V> list)? pageBuilder;
  Widget? gap;

  RefreshLoadState(
      {required this.initData,
      required this.getPage,
      required this.itemBuilder,
      this.wrapper,
      this.noMore,
      this.pageBuilder,
      this.gap});

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(_scrollEvent);
  }

  _scrollEvent() async {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      print('滑动到了最底部');
      if (_hasNext) {
        print("渲染第$_page页数据");
        await _getMore();
      } else {
        print("没有更多的数据了");
      }
    }
  }

  _buildChildren(List<V> pageList) {
    List<Widget> pageChildren = [];
    if (pageBuilder != null) {
      pageChildren = pageBuilder!(pageList);
    } else {
      pageList.forEach((e) {
        var item = itemBuilder(e);
        pageChildren.add(item);
        if (gap != null) {
          pageChildren.add(gap!);
        }
      });
    }
    _children += pageChildren;
    _page++;
  }

  _getMore() async {
    if (!_hasNext) {
      return;
    }
    var pageList = await getPage(_page, _pageSize);
    if (pageList.isEmpty) {
      _hasNext = false;
      return;
    }

    _buildChildren(pageList);
    if (_pageSize != pageList.length) {
      _hasNext = false;
    }

    print("下一页数:$_page, 当前总数${_children.length}");
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    _buildChildren(initData);
    var w = RefreshIndicator(
      onRefresh: () async {
        _page = 1;
        _children = [];
        await _getMore();
      },
      child: ListView(
        children: [
          ..._children,
          if (!_hasNext && noMore != null) noMore!(),
        ],
        controller: _scrollController,
      ),
    );
    return wrapper == null ? w : wrapper!(w);
  }
}
